﻿using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace SuperKit {
  /// <summary>
  /// BatchRename.xaml 的交互逻辑
  /// </summary>
  public partial class BatchRename : Window {

    public List<string> Paths { get; }
    public List<string> Backups { get; }
    public List<string> Extensions { get; }
    public List<TextBox> TextBoxs { get; set; }
    public delegate void OnNameChanged(int index, string name, string newName);
    public string FindText { get => txtFind.Text; set => txtFind.Text = value; }
    public string ReplaceText { get => txtReplace.Text; set => txtReplace.Text = value; }

    public bool UseRegex { get => checkUseRegex.IsChecked == true; set => checkUseRegex.IsChecked = value; }
    public bool IgnoreCase { get => checkCase.IsChecked == false; set => checkCase.IsChecked = (value == false); }
    public StringBuilder logs = new StringBuilder();

    public OnNameChanged Callback { get; set; }

    public BatchRename() {
      InitializeComponent();
      Paths = new List<string>();
      Backups = new List<string>();
      Extensions = new List<string>();
      logs = new StringBuilder();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e) {
      LoadAddition();
      Reload();
    }

    private void CreateButtonsFromString(string labels) {
      // 获取容器中现有的按钮文本
      var existingTexts = ButtonsContainer.Children
          .OfType<Button>()
          .Select(b => b.Content.ToString())
          .ToHashSet();  // 使用HashSet提高查找效率

      // 按逗号分割新字符串
      var newTexts = labels.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                          .Select(s => s.Trim())
                          .Where(s => !string.IsNullOrEmpty(s))
                          .Distinct();  // 确保新字符串本身没有重复

      // 为每个新字符串创建按钮（如果不存在）
      foreach (var text in newTexts) {
        if (!existingTexts.Contains(text)) {
          Button button = new Button {
            Content = text,
            Margin = new Thickness(3),
            Width = 80,
            Height = 20
          };

          button.Click += (sender, e) => {
            Button clickedButton = (Button)sender;
            string buttonText = clickedButton.Content.ToString();
            HandleButtonClick(buttonText);
          };

          ButtonsContainer.Children.Add(button);

          // 更新现有文本集合（避免同一批添加的重复）
          existingTexts.Add(text);
        }
      }
    }

    private void HandleButtonClick(string buttonText) {
      // 检查Shift键是否被按下
      bool isShiftPressed = (Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift;

      if (isShiftPressed) {
        // Shift键按下：拼接字符串
        if (!string.IsNullOrEmpty(txtFastSuffix.Text)) {
          // 如果文本框已有内容，添加分隔符后再拼接
          txtFastSuffix.Text += $"{buttonText}";
        } else {
          // 如果文本框为空，直接添加
          txtFastSuffix.Text = buttonText;
        }
      } else {
        // Shift键未按下：替换字符串
        txtFastSuffix.Text = buttonText;
      }
    }

    public void Add(List<string> paths) {
      Paths.AddRange(paths);
    }
    public void Add(string path) {
      Paths.Add(path);
    }
    public void Add(DirectoryInfo dir) {
      var dirs = dir.GetDirectories();
      foreach (var i in dirs) {
        Paths.Add(i.FullName);
        Extensions.Add("");
      }
      var files = dir.GetFiles();
      foreach (var i in files) {
        Paths.Add(i.FullName);
        Extensions.Add(i.Extension);
      }
    }


    private void LoadAddition() {
      string[] texts = ConfigReader.Instance.MarkArray;
      foreach (var text in texts) {
        MenuItem item_prefix = new MenuItem();
        menu_prefix.Items.Add(item_prefix);
        item_prefix.Header = text;
        item_prefix.Click += (o, e) => {
          txtAddition.Text = text;
          AddAddition(true);
          SetClipboard(text);
        };

        MenuItem item_suffix = new MenuItem();
        menu_suffix.Items.Add(item_suffix);
        item_suffix.Header = text;
        item_suffix.Click += (o, e) => {
          txtAddition.Text = text;
          AddAddition(false);
          SetClipboard(text);
        };

        MenuItem item_insert = new MenuItem();
        menu_insert.Items.Add(item_insert);
        item_insert.Header = text;
        item_insert.Click += (o, e) => {
          txtAddition.Text = text;
          AddAdditionCurrent();
          SetClipboard(text);
        };
      }
    }

    private void SetClipboard(string text) {
      if (Kit.IsEmpty(text)) {
        return;
      }

      try {
        Clipboard.SetText(text);
      } catch (Exception) {

      }
    }

    private void SetAddition(object sender, RoutedEventArgs e) {

    }


    private void Reload() {
      TextBoxs = new List<TextBox>(Paths.Count);
      foreach (var dir in Paths) {
        TextBox txt = new() {
          Text = Path.GetFileName(dir),
          Margin = new Thickness(0, 2, 0, 0)
        };
        list_files.Children.Add(txt);
        TextBoxs.Add(txt);
      }
    }

    private void buttonBatchRename_Click(object sender, RoutedEventArgs e) {
      ExecuteBatchRename();
    }

    private void ExecuteBatchRename() {
      for (int i = 0; i < Paths.Count; i++) {
        var txt = TextBoxs[i].Text;
        var src = Paths[i];
        var path = Path.Combine(Path.GetDirectoryName(src), txt);

        if (src.Equals(path)) { // 没有改变
          continue;
        }

        // 根据是文件还是目录分开处理
        AutoMove(src, path);

        Paths[i] = path;

        Callback?.Invoke(i, src, path);
      }

      Kit.Beep();
    }

    public void AutoMove(string src, string dest) {
      if (Directory.Exists(src)) {
        if (Directory.Exists(dest)) {
          dest = Kit.GetNonExistDirName(dest);
        }

        try {
          Directory.Move(src, dest);
        } catch (IOException e) {
          Flush(e.Message);
        }

      } else {
        if (File.Exists(dest)) {
          dest = Kit.GetNonExistName(dest);
        }

        File.Move(src, dest);
      }
    }

    private void Flush(string message) {
      Dispatcher.Invoke(() => {
        txtLogs.Content = message;
        logs.Append(message);
        logs.Append("\r\n");
      });
    }

    private void buttonFavorStar_Click(object sender, RoutedEventArgs e) {
      foreach (var text in TextBoxs) {
        text.Text = Kit.ToggleFavorStar(text.Text);
      }
    }


    private void buttonAddFront_ButtonClick(object sender, RoutedEventArgs e) {
      AddAddition(true);
    }

    private void buttonAddBack_ButtonClick(object sender, RoutedEventArgs e) {
      AddAddition(false);
    }

    private void AddAddition(bool isFront) {
      string add = txtAddition.Text;
      if (Kit.IsEmpty(add)) {
        return;
      }

      foreach (var text in TextBoxs) {
        var s = text.Text;
        // 如果已经存在，则清除，否则增加
        if (s.Contains(add)) {
          text.Text = s.Replace(add, "");
        } else {
          if (isFront) {
            text.Text = add + s;
          } else {
            // 插入后缀有些区别，不能直接插入到最后，而是要插入到扩展名的前面
            string ext = Path.GetExtension(s);
            if (Kit.IsEmpty(ext)) { // 如果没有扩展名，则不处理
              text.Text = s + add;
            } else {
              string pureName = Path.GetFileNameWithoutExtension(s);
              text.Text = $"{pureName}{add}{ext}";
            }



          }
        }
      }
    }

    private void buttonFastInput_Click(object sender, RoutedEventArgs e) {

    }

    private void buttonAddInsert_ButtonClick(object sender, RoutedEventArgs e) {
      AddAdditionCurrent();
    }

    private void AddAdditionCurrent() {
      string add = txtAddition.Text;
      if (Kit.IsEmpty(add)) {
        return;
      }

      // 查找当前活动项目
      foreach (var i in TextBoxs) {
        if (i.IsFocused) {
          var s = i.Text;
          i.Text = s.Insert(i.SelectionStart, add);
          return;

        }
      }
    }

    private void Backup() {
      // 对项目进行一次备份
      Backups.Clear();
      foreach (var text in TextBoxs) {
        Backups.Add(text.Text);
      }
    }

    private void buttonFindAndReplace_Click(object sender, RoutedEventArgs e) {
      Backup();

      foreach (var text in TextBoxs) {
        text.Text = Replace(text.Text);
      }
    }

    private void CancelReplace_Click(object sender, RoutedEventArgs e) {
      for (int i = 0; i < TextBoxs.Count; i++) {
        TextBoxs[i].Text = Backups[i];
      }
    }


    public string Replace(string s) {
      if (Kit.IsEmpty(FindText)) {
        return s;
      }

      if (UseRegex) {
        Regex regex = new Regex(FindText);
        s = regex.Replace(s, ReplaceText);
      } else {
        if (IgnoreCase) {
          int pointer = 0;
          while (true) {
            int index = s.IndexOf(FindText, pointer, StringComparison.OrdinalIgnoreCase);
            if (index == -1) {
              break;
            }
            string front = s.Substring(0, index);
            string rear = s.Substring(index + FindText.Length);
            s = front + ReplaceText + rear;
            pointer = index + ReplaceText.Length;
          }
        } else {
          s = s.Replace(FindText, ReplaceText);
        }
      }
      return s;
    }

    private void OpenMain_Click(object sender, RoutedEventArgs e) {
      MainWindow mainWindow = new MainWindow();
      mainWindow.Show();
    }

    private void Settings_Click(object sender, RoutedEventArgs e) {
      SettingsWindow settingsWindow = new SettingsWindow();
      settingsWindow.ShowDialog();
    }

    private void Exit_Click(object sender, RoutedEventArgs e) {
      Close();
    }

    private void Logs_Click(object sender, MouseButtonEventArgs e) {
      LogsWindow dlg = new LogsWindow();
      dlg.Logs = logs.ToString();
      dlg.ShowDialog();
    }

    private void AddExtension_ButtonClick(object sender, RoutedEventArgs e) {
      Backup();
      for (int i = 0; i < TextBoxs.Count; i++) {
        TextBoxs[i].Text = RemoveFileExtension(TextBoxs[i].Text) + Extensions[i];
      }
    }

    public static string RemoveFileExtension(string fileName) {
      // 处理空值或空白字符串
      if (string.IsNullOrWhiteSpace(fileName))
        return fileName;

      // 使用Path类安全地获取不带扩展名的文件名
      return Path.GetFileNameWithoutExtension(fileName);
    }

    private void RemoveExtension_ButtonClick(object sender, RoutedEventArgs e) {
      Backup();
      for (int i = 0; i < TextBoxs.Count; i++) {
        TextBoxs[i].Text = RemoveFileExtension(TextBoxs[i].Text);
      }
    }

    private void OnAddFastSuffixList(object sender, RoutedEventArgs e) {
      CreateButtonsFromString(txtFastSuffixList.Text);
    }

    private void OnClearFastSuffix(object sender, RoutedEventArgs e) {
      txtFastSuffix.Text = string.Empty;
    }
  }
}
